package server;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.net.ssl.*;
import msgs.*;

/**
 * Constantly sends out messages from the queue to the clients
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */


public class ClientSender extends Thread implements TTConstants {
	private Socket sock;
	private int port;
	private boolean go;
	
	/**
	 * Outgoing queue of messages
	 */
	protected static Vector<ClientMsg> outQ;
	
	private ClientMsg cmsg;
	private ObjectOutputStream oos;
	////private final static String TS_PATH = "servers.jks"; // trusted servers
	//private final static String TS_PASS = "changeit";
	//final String[] enabledCipherSuites = { "SSL_DH_anon_WITH_RC4_128_MD5" };
	
	public ClientSender(int port) {
		this.port = port;
		outQ = new Vector<ClientMsg>();
		go = true;
		//System.setProperty("javax.net.ssl.trustStore", TS_PATH);
		//System.setProperty("javax.net.ssl.trustStorePassword", TS_PASS);
	}
	
	public void run() {
		while (go) {
			if (!(outQ.isEmpty())) {
				cmsg = outQ.remove(0);
				try { 
					sock = new Socket();
					sock.connect(new InetSocketAddress(cmsg.getIp(), port), 4000); // yay, timeouts? I'm not convinced this actually works
																					// but it's also crazy hard to test
					oos = new ObjectOutputStream(sock.getOutputStream());
					oos.writeObject(cmsg);
					oos.flush();
					oos.close();
					//sock.close();
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
			else {
				try {
					Thread.sleep(100);	// sleep if there's no work
				}
				catch (InterruptedException e) {
					e.printStackTrace(); 
				}
			}
		}
	}
	
	/**
	 * Mercilessly kills the sender queue
	 */
	public void killClientSender() {
		go = false;
	}
}
